const scpClient = require('scp2');
const ora = require('ora');
const chalk = require('chalk');
const server = require('./products');
const spinner = ora(
    '正在发布到' +
  (process.env.NODE_ENV === 'prod' ? '生产' : '测试') +
  '服务器...'
);

var Client = require('ssh2').Client;

var conn = new Client();
conn
    .on('ready', function () {
        console.log(789);

        // rm 删除dist文件，\n 是换行 换行执行 重启nginx命令 我这里是用docker重启nginx
        conn.exec('cd /home/shopplus/front/admin-shop && cd /usr/local/openresty/nginx/sbin && ./nginx -s reload', function (
            err,
            stream
        ) {
            console.log(456, err);
            if (err) { throw err; }
            stream
                .on('close', function (code, signal) {
                    // 在执行shell命令后，把开始上传部署项目代码放到这里面
                    spinner.start();
                    scpClient.scp('./admin-shop',
                        {
                            host: server.host,
                            port: server.port,
                            username: server.username,
                            password: server.password,
                            path: server.path,
                            progress: (transferred, total, filename) => {
                                console.log(`文件${filename}上传进度: ${transferred} / ${total}`);
                            }
                        },
                        function (err) {
                            spinner.stop();
                            if (err) {
                                console.log(chalk.red('发布失败.\n'));
                                throw err;
                            } else {
                                console.log(chalk.green('Success! 成功发布到' + (process.env.NODE_ENV === 'prod' ? '生产' : '测试') + '服务器! \n'));
                            }
                        }
                    );
                    conn.end();
                })
                .stdout.on('data', function (data) {
                    console.log('STDOUT: ' + data);
                })
                .stderr.on('data', function (data) {
                    console.log('STDERR: ' + data);
                });
        });
    })
    .on('error', function (err) {
        console.error('SSH连接错误:', err);
        process.exit(1); // 或者其他错误处理逻辑
    })
    .connect({
        host: server.host,
        port: server.port,
        username: server.username,
        password: server.password
    });
